package com.topnav.mc.uitls;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.js.lib.cache.Cache;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.entity.DeviceLog;
import com.topnav.mc.admin.service.IDeviceLogService;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.position.PositionInfo;
import com.topnav.mc.position.PositionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.topnav.mc.common.Constant.DEVICE_CURRENT_STATUS;

/**
 * @Author: kenny
 * @Date: 2023/10/31 17:24
 */
@Component
public class DeviceOnlineUtils {

    //private ConcurrentHashMap<String,Object> deviceMap = new ConcurrentHashMap<String,Object>();

    @Resource(name="sysCache")
    private Cache sysCache;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceLogService deviceLogService;
    @Autowired
    private PositionUtil positionUtil;
    private String suffix="KEEPALIVE-DEVICE-";
    private long expire=3*60;


    public DeviceOnlineUtils(){
        /** 下一次执行时间是以上一次执行完时间加上  interval */
/*        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() ->{
            try {
            //根据数据量 动态加消费端
            List<Device> list = deviceService.getAllFromCache();

            Integer count = MsgQueueUtil.getInstance().size(GPS_QUEUE_TOPIC);
            if (count > 0){
                * 动态增加消费线程数
                for(int i=0;i<=count/batch;i++){
                    if (i+1>max_tread){break;}
                    gpsPollTask.execute(null);
                }
            }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }, 10, 10, TimeUnit.SECONDS);*/
    }
    /**
     * 设置在线
     */
    public void setOnline(String deviceCode){
/*        if (RedisUtil.hasKey(suffix + deviceCode)){
            RedisUtil.expire(suffix + deviceCode,expire);
        }else{
            RedisUtil.set(suffix + deviceCode,1,expire);
        }*/

/*        if (!this.isOnline(deviceCode)){
            this.deviceStatusEvent(deviceService.getFromCache(deviceCode),1);
        }*/
        sysCache.hset(DEVICE_CURRENT_STATUS, deviceCode, 1,expire);
    }

    /**
     * 设置是否在线
     */
    public boolean isOnline(String deviceCode){
        //return RedisUtil.hasKey(suffix + deviceCode);
        return sysCache.hget(DEVICE_CURRENT_STATUS, deviceCode) != null;
    }

    /**
     * 设置离线
     */
    public void setOffline(String deviceCode){
/*        if (RedisUtil.hasKey(suffix + deviceCode)){
            RedisUtil.expire(suffix + deviceCode,1);
        }*/

/*        if (this.isOnline(deviceCode)){
            this.deviceStatusEvent(deviceService.getFromCache(deviceCode),0);
        }*/
        sysCache.hdel(DEVICE_CURRENT_STATUS, deviceCode);

    }

    /**
     * 状态变化时要做的事情，
     * 1、更新数据库
     * 2、更新日志
     * 3、刚上线就同步通道信息
     * @param device
     * @param newStatus
     */
    public void deviceStatusEvent(Device device, Integer newStatus,String msg){
        if (device == null || newStatus == null){
            return;
        }

        //更新Device表
        if (device.getOnline() && newStatus == 1){return;}
        if (!device.getOnline() && newStatus == 0){return;}

        device.setOnline(newStatus==1?true:false);
        deviceService.saveToCache(device);

        UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("online",newStatus==1?true:false);
        updateWrapper.eq("id",device.getId());
        deviceService.update(updateWrapper);

        //更新DeviceLog表
        DeviceLog deviceLog = new DeviceLog();
        deviceLog.setDeviceId(device.getId());
        deviceLog.setDeviceCode(device.getCode());
        deviceLog.setAction(newStatus);
        //取得当前位置
        PositionInfo positionInfo = null;
        if ((positionInfo = positionUtil.getCurrentPosition(device.getCode())) != null){
            ;
            deviceLog.setLongitude(String.valueOf(positionInfo.getLongitude()));
            deviceLog.setLatitude(String.valueOf(positionInfo.getLatitude()));
            deviceLog.setCoordinateSystem(positionInfo.getCoordinateSystem());
        }else{
            deviceLog.setLongitude(MapUtil.getCenterPoint().get("longitude").toString());
            deviceLog.setLatitude(MapUtil.getCenterPoint().get("latitude").toString());
            deviceLog.setCoordinateSystem(device.getCoordinateSystem());
        }
        deviceLog.setCreateTime(new Date());
        deviceLog.setNote(msg);
        deviceLogService.save(deviceLog);

        device.setOnOfflineEvent(newStatus);
        device.setEventTime(new Date());
        deviceService.saveToCache(device);

        //刚上线则同步通道信息
        if (newStatus == 1){
           this.syncDeviceChannel(device);
        }
    }

    @Async("taskExecutor")
    public void syncDeviceChannel(Device device){
        deviceService.syncDeviceChannel(device);
    }


}
